<template>
	<view class="dashboard">
		<!-- 调试：角色切换 -->
		<view class="debug-role" v-if="debug">
			<text class="role-tag" :class="{ active: currentRole === r }" v-for="r in [1, 2, 3, 4]" :key="r" @click="setRole(r)">
				{{ roleName(r) }}
			</text>
		</view>

		<!-- 头部 -->
		<view class="header">
			<image class="logo" src="@/static/logo.png"></image>
			<text class="welcome">欢迎回来，{{ roleName(currentRole) }}</text>
			<text class="subtitle">数据驱动决策，洞察先人一步</text>
		</view>

		<!-- 内容区 -->
		<scroll-view class="content" scroll-y>
			<!-- 总经理 -->
			<block v-if="currentRole === 1">
				<view class="section">
					<text class="section-title">📊 订单统计</text>
					<view class="card-grid">
						<DataCard v-for="(item, i) in ceoStats" :key="i" :data="item" />
					</view>
				</view>

				<view class="section">
					<text class="section-title">🔁 订单复购分析</text>
					<view class="rebuy-box">
						<text class="amount">
							复购总金额
							<text class="num">¥2,847,320</text>
						</text>
						<text class="amount">
							复购平均金额
							<text class="num">¥867</text>
						</text>
					</view>
				</view>

				<view class="section">
					<text class="section-title">📈 订单趋势</text>
					<PeriodSelector v-model="selectedPeriod" />
					<TrendChart :loading="loading" :data="ceoTrend" />
				</view>
			</block>

			<!-- 业务经理 -->
			<block v-else-if="currentRole === 2">
				<TabSwitcher v-model="viewMode" :tabs="['个人数据', '团队数据']" />

				<view class="section">
					<text class="section-title">🎯 {{ viewMode === 0 ? '个人' : '团队' }}业绩趋势</text>
					<PeriodSelector v-model="selectedPeriod" />
					<TrendChart :loading="loading" :data="managerTrend" />
				</view>

				<view class="section">
					<text class="section-title">💰 业绩组成</text>
					<qiun-data-charts type="column" :chartData="managerComposition" />
				</view>

				<view class="section">
					<text class="section-title">🏆 团队排名</text>
					<RankList :list="managerRanks" />
				</view>
			</block>

			<!-- 销售 -->
			<block v-else-if="currentRole === 3">
				<view class="section">
					<text class="section-title">💼 个人业绩</text>
					<PeriodSelector v-model="selectedPeriod" />
					<TrendChart :loading="loading" :data="salesTrend" />
				</view>
			</block>

			<!-- 客服 -->
			<block v-else-if="currentRole === 4">
				<view class="section">
					<text class="section-title">📦 复购发货趋势</text>
					<PeriodSelector v-model="selectedPeriod" />
					<TrendChart :loading="loading" :data="supportTrend" type="area" />
				</view>
			</block>
		</scroll-view>
	</view>
</template>

<script setup>
import { ref, watch } from 'vue';
import DataCard from '@/components/charts/DataCard.vue';
import TabSwitcher from '@/components/charts/TabSwitcher.vue';
import RankList from '@/components/charts/RankList.vue';
import PeriodSelector from '@/components/charts/PeriodSelector.vue';
import TrendChart from '@/components/charts/TrendChart.vue';

// API
import { fetchDashboardData } from '@/api/dashboard';

// 状态
const debug = ref(true);
const currentRole = ref(1);
const viewMode = ref(0);
const loading = ref(false);

// 从缓存读取上次周期
const savedPeriod = uni.getStorageSync('dashboard_period') || '月';
const selectedPeriod = ref(savedPeriod);

// 保存周期选择
watch(selectedPeriod, (val) => {
	uni.setStorageSync('dashboard_period', val);
});

// 切换角色
const setRole = (role) => {
	currentRole.value = role;
	viewMode.value = 0;
};

const roleName = (role) => ({ 1: '总经理', 2: '业务经理', 3: '销售员', 4: '客服' }[role]);

// 趋势图数据
// 初始化时给默认值（避免 undefined 导致不渲染）
const ceoTrend = ref({
	categories: [],
	series: []
});

const salesTrend = ref({
	categories: [],
	series: []
});

const supportTrend = ref({
	categories: [],
	series: []
});

const managerTrend = ref({
	categories: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月'],
	series: [{ name: '订单数', data: [120, 135, 148, 160, 175, 190, 205, 220] }]
});

const managerComposition = ref({
	categories: ['A类', 'B类', 'C类', 'D类'],
	series: [{ name: '金额', data: [40, 30, 20, 10] }]
});

const managerRanks = ref([
	{ name: '张三', score: 98 },
	{ name: '李四', score: 92 },
	{ name: '王五', score: 88 },
	{ name: '赵六', score: 85 }
]);

const ceoStats = ref([
	{ label: '年度订单', value: '2,847', color: '#007AFF' },
	{ label: '复购订单', value: '1,203', color: '#58B6FF' },
	{ label: '复购率', value: '42.3%', color: '#FFB400' },
	{ label: '平均金额', value: '¥867', color: '#FF7900' }
]);

// 监听变化，加载数据
watch(
	[selectedPeriod, currentRole],
	async () => {
		if (![1, 3, 4].includes(currentRole.value)) return;

		loading.value = true;
		try {
			const res = await fetchDashboardData(currentRole.value, selectedPeriod.value);
			if (currentRole.value === 1) ceoTrend.value = res.trend;
			if (currentRole.value === 3) salesTrend.value = res.trend;
			if (currentRole.value === 4) supportTrend.value = res.trend;
		} catch (err) {
			console.error('加载失败', err);
		} finally {
			loading.value = false;
		}
	},
	{ immediate: true }
);

// 图表配置
const padding = ref([15, 10, 15, 35]);
const extra = ref({ line: { linearCategoryGradient: true, type: 'curve', width: 2 } });
const opts = ref({
	xAxis: { disabled: false, axisLine: true, axisLineColor: '#cccccc', fontColor: '#666666' },
	yAxis: { disabled: false, splitNumber: 5 },
	legend: { show: true, position: 'top' },
	dataLabel: false,
	enableScroll: false
});
</script>

<style lang="scss" scoped>
/* 你的原有样式保持不变 */
$primary: #007aff;
$bg: #f8f9fb;
$card-bg: #ffffff;
$radius: 16px;
$shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.08);

.dashboard {
	min-height: 100vh;
	background: $bg;
}

.content {
	padding: 0 30rpx 40rpx;
}

.section {
	margin-bottom: 40rpx;
}
.section-title {
	font-size: 32rpx;
	color: #333;
	margin-bottom: 24rpx;
}

.card-grid {
	display: flex;
	flex-wrap: wrap;
	gap: 20rpx;
}

.chart-container {
	width: 100%;
	height: 400rpx;
	background: #fff;
	border-radius: $radius;
	box-shadow: $shadow;
	overflow: hidden;
	margin-top: 20rpx;
}

.loading {
	display: flex;
	justify-content: center;
	align-items: center;
	height: 100%;
	font-size: 32rpx;
	color: #999;
}
</style>

<style lang="scss" scoped>
$primary: #007aff;
$bg: #f8f9fb;
$card-bg: #ffffff;
$radius: 16rpx;
$shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.08);

.dashboard {
	min-height: 100vh;
	background: $bg;
	font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
}

.debug-role {
	position: fixed;
	top: 20px;
	right: 20px;
	z-index: 999;
	display: flex;
	gap: 10rpx;
}

.role-tag {
	padding: 8rpx 16rpx;
	background: #ddd;
	border-radius: 30rpx;
	font-size: 24rpx;
	&.active {
		background: $primary;
		color: white;
	}
}

.header {
	background: linear-gradient(135deg, $primary, #58b6ff);
	padding: 60rpx 40rpx 40rpx;
	text-align: center;
	color: white;
	border-bottom-left-radius: $radius;
	border-bottom-right-radius: $radius;
	margin-bottom: 30rpx;
}

.logo {
	width: 120rpx;
	height: 120rpx;
	border-radius: 50%;
	border: 4rpx solid rgba(255, 255, 255, 0.3);
	margin-bottom: 20rpx;
}

.welcome {
	font-size: 36rpx;
	font-weight: 600;
	display: block;
	margin-bottom: 10rpx;
}

.subtitle {
	font-size: 26rpx;
	opacity: 0.9;
}

.content {
	padding: 0 30rpx 40rpx;
}

.chart-container {
	width: 100%;
	height: 400rpx; /* 必须设置高度 */
	background: #ffffff;
	border-radius: $radius;
	box-shadow: $shadow;
	overflow: hidden;
	margin-top: 20rpx;
}

.section {
	margin-bottom: 40rpx;
}

.section-title {
	font-size: 32rpx;
	color: #333;
	margin-bottom: 24rpx;
	font-weight: 500;
	display: block;
}

.card-grid {
	display: flex;
	flex-wrap: wrap;
	gap: 20rpx;
}

.rebuy-box {
	background: $card-bg;
	padding: 30rpx;
	border-radius: $radius;
	box-shadow: $shadow;
	display: flex;
	justify-content: space-between;
	align-items: center;
	flex-wrap: wrap;
	gap: 20rpx;
}

.amount {
	font-size: 28rpx;
	color: #666;
	.num {
		color: $primary;
		font-weight: bold;
		font-size: 32rpx;
		margin-left: 10rpx;
	}
}

.team-list {
	background: $card-bg;
	border-radius: $radius;
	overflow: hidden;
	box-shadow: $shadow;
}

.team-item {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 24rpx 30rpx;
	border-bottom: 1rpx solid #eee;
	&:last-child {
		border-bottom: none;
	}
}

.count {
	font-weight: bold;
	color: #f00;
	margin: 0 20rpx;
}

.btn {
	padding: 10rpx 20rpx;
	background: #007aff;
	color: white;
	font-size: 24rpx;
	border-radius: 8rpx;
}

.status-row {
	display: flex;
	flex-direction: column;
	gap: 16rpx;
	font-size: 28rpx;
	color: #555;
	.pending {
		color: #f50;
		font-weight: bold;
	}
	.done {
		color: #0a0;
		font-weight: bold;
	}
}
</style>
